package gold.digger;

import gold.vo.TreeNode;
import javafx.util.Pair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC814 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public TreeNode pruneTree(TreeNode root) {
            final Pair<TreeNode, Integer> res = pruneTreeRecur(root);
            if (res.getValue().intValue() == 0) return null;
            return res.getKey();
        }

        public Pair<TreeNode, Integer> pruneTreeRecur(TreeNode root) {
            if (null == root) return new Pair<>(null, 0);
            Pair<TreeNode, Integer> leftSide = pruneTreeRecur(root.left);
            Pair<TreeNode, Integer> rightSide = pruneTreeRecur(root.right);
            if (leftSide.getValue().intValue() == 0) root.left = null;
            if (rightSide.getValue().intValue() == 0) root.right = null;
            return new Pair<>(root, leftSide.getValue() + rightSide.getValue() + root.val);
        }
    }

    public void run() {
        Solution solution = new Solution();
        TreeNode root = TreeNode.createTree("[1,1,0,1,1,0,1,0]");
        final TreeNode re = solution.pruneTree(root);
        System.out.println(re);
    }

    public static void main(String[] args) throws Exception {
        LC814 an = new LC814();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
